package main

//获取bko包解释的时间
import (
	"bufio"
	"fmt"
	"github.com/axgle/mahonia"
	"io"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"
)

//逐行读取文件
func ReadLine(fileName string, handler func(string)) error {
	f, err := os.Open(fileName)
	if err != nil {
		return err
	}
	buf := bufio.NewReader(f)
	for {
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		handler(line)
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
	}
	return nil
}

func main() {
	var filePath string
	args := os.Args
	if args != nil && len(args) > 1 {
		filePath = string(args[1])
		if string(filePath[1:2]) != ":" { //非根目录
			filePath = getCurrentDirectory() + filePath
			fmt.Println(filePath)
		}
	}

	var fileName string
	var starTime string
	var endTime string
	var count int
	var allTime float64
	fileNameExp := regexp.MustCompile(`ZHBKO.*\d`)
	timeExp := regexp.MustCompile(`[\d]{2}:[\d]{2}:[\d]{2}`)

	// saveAs := "E:\\qq\\916793573\\FileRecv\\bko日志\\bkotime.csv"

	fileInfo, err := os.Stat(filePath)
	if err != nil {
		if os.IsNotExist(err) {
			fmt.Println("文件不存在！")
			return
		}
	}
	if fileInfo.IsDir() {
		fmt.Println("该路径是文件夹！")
		return
	}

	i := strings.LastIndex(filePath, "\\")
	saveFile := string(filePath[0:i+1]) + "bkoTime.csv"

	//要保存的文件
	file, error := os.Create(saveFile)
	defer file.Close()
	if error != nil {
		fmt.Println(error)
	}
	file.WriteString("文件名称  ,开始时间  ,结束时间  ,耗时（秒）  \r\n")

	doc := mahonia.NewDecoder("gbk")
	ReadLine(filePath, func(line string) {
		content := doc.ConvertString(string(line))
		//字符串匹配
		if strings.Contains(content, "txt.gz") &&
			(strings.Contains(content, "FILE") || strings.Contains(content, "DB Temp")) {
			// fmt.Println(content)
			//正则表达式提取文件名和时间
			if strings.Contains(content, "FILE") {
				fileName = fileNameExp.FindString(content)
				starTime = timeExp.FindString(content)
			} else {
				fileName2 := fileNameExp.FindString(content)
				endTime = timeExp.FindString(content)
				if fileName == fileName2 {
					count++
					t1, _ := time.Parse("15:04:05", starTime)
					t2, _ := time.Parse("15:04:05", endTime)
					allTime += t2.Sub(t1).Seconds()
					fmt.Printf("%s  %s, %s  耗时: %v s\n", fileName, starTime, endTime, t2.Sub(t1).Seconds())
					//float转换 strconv.FormatFloat
					data := fileName + ", " + starTime + ", " + endTime + ", " + strconv.FormatFloat(t2.Sub(t1).Seconds(), 'f', 0, 64) + "\r\n"
					file.WriteString(data) //写文件
				}
			}
		}
	})
	//格式化输出
	dat := fmt.Sprintf("总文件个数: %v ，总耗时 %v s ，平均：%.2f s\n", count, allTime, allTime/float64(count))
	file.WriteString(dat)
	// file.WriteString("总文件个数: " + strconv.Itoa(count) + " , 总耗时" + strconv.Itoa(allTime) + "平均" + strconv.ParseFloat(allTime/float64(count)))
	fmt.Println(dat)

}
func getCurrentDirectory() string {
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	// fmt.Println(dir)
	return strings.Replace(dir, "\\", "/", -1) + "/"
}
